package com.why.usercenter.controller;

import com.google.gson.Gson;
import com.why.commonresults.Result;
import com.why.servicebase.exception.GuilException;
import com.why.usercenter.bean.UcenterMember;
import com.why.usercenter.service.UcenterMemberService;
import com.why.usercenter.wx.WxUtils;
import com.why.utils.HttpClientUtils;
import com.why.utils.JwtUtils;
import org.apache.tomcat.jni.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.UUID;

/**
 * @program: guli_parent
 * @description:
 * @author: @why
 * @create: 2021-02-19 19:59
 **/
@Controller
@RequestMapping("/api/ucenter/wx")
@CrossOrigin
public class WxController {

    @Autowired
    private UcenterMemberService member;

    /**
     * 扫码成功后的callback函数,获取扫码人的信息
     * state:原样信息
     * code：类似手机的验证码，唯一的随机值
     *
     * @return
     */

    @GetMapping("/callback")
    public String callbackWx(String code, String state) {
        //1.获取code


        //2.根据code获取访问的token和appid
        String baseAccessTokenUrl =
                "https://api.weixin.qq.com/sns/oauth2/access_token" +
                        "?appid=%s" +
                        "&secret=%s" +
                        "&code=%s" +
                        "&grant_type=authorization_code";
        String accessTokenUrl = String.format(baseAccessTokenUrl,
                WxUtils.WX_OPEN_APP_ID,
                WxUtils.WX_OPEN_APP_SECRET,
                code);
        //3.请求这2个值，获取token和appid，使用httpclient进行请求
        String token = null;
        try {
            token = HttpClientUtils.get(accessTokenUrl);
//            System.out.println("token--->"+token);
        } catch (Exception e) {
            throw new GuilException(20001, "获取token失败！");
        }

        //4.将得到的数据转为map集合,并获取对应的数据  accessToken，openid
        Gson gson = new Gson();
        HashMap map = gson.fromJson(token, HashMap.class);
        System.out.println(map);
        String accessToken = (String) map.get("access_token");
        String openid = (String) map.get("openid");

        //7.将扫描人的信息加入数据库,先判断有无人，再判断是否应该添加
        UcenterMember user = member.getMemberByOpenId(openid);
        //如果是空则加入数据，否则就是进行登录
        if (user == null) {
            //5，使用 accessToken，openid获取扫描人的信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
            String resultUserInfo = null;
            try {
                resultUserInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("resultUserInfo==========" + resultUserInfo);
            } catch (Exception e) {
                throw new GuilException(20001, "获取用户信息失败");
            }
            //6 将得到的用户信息解析
            HashMap<String, Object> mapUserInfo = gson.fromJson(resultUserInfo,
                    HashMap.class);
            String nickname = (String) mapUserInfo.get("nickname");
            System.out.println(nickname);

            String headimgurl = (String) mapUserInfo.get("headimgurl");
            System.out.println(headimgurl);
           user=new UcenterMember();
            user.setNickname(nickname);
            user.setOpenid(openid);
            user.setAvatar(headimgurl);

            member.save(user);
        }
        //使用jwt生成token，
        System.out.println(user.getId()+user.getNickname());
        String jwtToken = JwtUtils.getJwtToken(user.getId(), user.getNickname());

//解决了跨域问题
        return "redirect:http://localhost:3000?token="+jwtToken;
    }


    /**
     * 生成微信扫描二维码
     */
    @GetMapping("/wxqrcode")
    public String createWxCode() {
        //访问的微信的url  %s，这些都是占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        //对重定向的url进行编码
        String Url = null;
        try {
            Url = URLEncoder.encode(WxUtils.WX_OPEN_REDIRECT_URL, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new GuilException(20001, "重定向编码失败");
        }

        // 防止csrf攻击（跨站请求伪造攻击）
//String state = UUID.randomUUID().toString().replaceAll("-", "");//一般情况下会使用一个随机数
        String state = UUID.randomUUID().toString().replaceAll("-", "");

        //设置重定向的url
        baseUrl = String.format(baseUrl, WxUtils.WX_OPEN_APP_ID, Url, state);
        System.out.println("base:" + baseUrl);
        //重定向到微信地址页面
        return "redirect:" + baseUrl;
    }


}
